/**
 * 会议助手WebSocket客户端
 * 基于API文档实现的WebSocket连接和消息处理
 */
// 定义配置枚举
// 【会议纪要】 - MeetingMinutes
// 【洞察】 - Abstract + Advice + RiskAndDependency (洞察子项)
// 【关键点】- keypoint
// 【待办】 - ToDo
// 【转录】
const NotificationTypes = {
  MeetingMinutes: 'MeetingMinutes',
  // 洞察子项
  Abstract: 'Abstract',           // 摘要
  Advice: 'Advice',               // 建议
  RiskAndDependency: 'RiskAndDependency', // 风险与依赖
  keypoint: 'keypoint',
  ToDo: 'Todo',
};
class MeetingAssistantClient {
    constructor(serverUrl = 'ws://10.198.66.254:30080/ws') {
        this.serverUrl = serverUrl;
        this.ws = null;
        this.sessionId = null;
        this.pingInterval = null;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 1000; // 1秒
        this.isConnected = false;
        this.handleNotification = null;
        
        // 事件回调
        this.onConnected = null;
        this.onDisconnected = null;
        this.onResponse = null;
        this.onNotification = null;
        this.onStatus = null;
        this.onError = null;
        this.onHeartbeat = null;
    }

    /**
     * 连接到服务器
     * @returns {Promise<string>} 返回session_id
     */
    connect() {
        return new Promise((resolve, reject) => {
            try {
                this.ws = new WebSocket(this.serverUrl);
                
                this.ws.onopen = () => {
                    console.log('WebSocket连接已建立');
                    this.isConnected = true;
                    this.reconnectAttempts = 0;
                    
                    if (this.onConnected) {
                        this.onConnected();
                    }
                };
                
                this.ws.onmessage = (event) => {
                    try {
                        const msg = JSON.parse(event.data);
                        this.handleMessage(msg);
                        
                        // 连接成功后获取session_id
                        if (msg.type === 'status' && msg.data && msg.data.session_id) {
                            this.sessionId = msg.data.session_id;
                            console.log('会话已创建:', this.sessionId);
                            resolve(this.sessionId);
                        }
                        this.startPing();// 启动心跳
                    } catch (error) {
                        console.error('解析消息失败:', error);
                    }
                };
                
                this.ws.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    this.isConnected = false;
                    
                    if (this.onError) {
                        this.onError(error);
                    }
                    
                    reject(error);
                };
                
                this.ws.onclose = (event) => {
                    console.log('WebSocket连接已关闭', event.code, event.reason);
                    this.isConnected = false;
                    this.stopPing();
                    
                    if (this.onDisconnected) {
                        this.onDisconnected(event);
                    }
                    
                    // 自动重连
                    this.attemptReconnect();
                };
                
            } catch (error) {
                console.error('创建WebSocket连接失败:', error);
                reject(error);
            }
        });
    }

    /**
     * 尝试重连
     */
    attemptReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
            
            setTimeout(() => {
                this.connect().catch(error => {
                    console.error('重连失败:', error);
                });
            }, this.reconnectDelay * this.reconnectAttempts);
        } else {
            console.error('达到最大重连次数，停止重连');
        }
    }

    /**
     * 发送ASR文本（不带说话人）
     * @param {string} text 文本内容
     * @param {string} id 音频片段ID
     */
    sendASRText(text,id) {
        if (!this.isConnected || !this.ws) {
            console.error('WebSocket未连接');
            return;
        }
        
        const message = {
            type: 'asr_text',
            data: {
            text: text,
            id: id
            }
        };
        
        try {
            this.ws.send(JSON.stringify(message));
            console.log('已发送ASR文本:', text);
        } catch (error) {
            console.error('发送ASR文本失败:', error);
        }
    }

    /**
     * 发送ASR文本（带说话人）
     * @param {string} speaker 说话人
     * @param {string} text 文本内容
     * @param {string} id 音频片段ID
     */
    sendASRSpeakerText(speaker, text, id) {
        if (!this.isConnected || !this.ws) {
            console.error('WebSocket未连接');
            return;
        }
        
        const message = {
            type: 'asr_speaker_text',
            data: {
                speaker: speaker,
                text: text,
                id: id
            }
        };
        
        try {
            this.ws.send(JSON.stringify(message));
            console.log('已发送ASR说话人文本:', speaker, text);
        } catch (error) {
            console.error('发送ASR说话人文本失败:', error);
        }
    }

    /**
     * 发送心跳消息
     */
    sendHeartbeat() {
        if (!this.isConnected || !this.ws) {
            console.error('WebSocket未连接');
            return;
        }
        
        const message = {
            type: 'Ping'
        };
        
        try {
            this.ws.send(JSON.stringify(message));
            console.log('已发送心跳消息');
        } catch (error) {
            console.error('发送心跳消息失败:', error);
        }
    }

    /**
     * 开始定时发送心跳（每20秒）
     */
    startPing() {
        this.stopPing(); // 先停止之前的定时器
        
        this.pingInterval = setInterval(() => {
            this.sendHeartbeat();
        }, 20000); // 20秒
        
        console.log('已启动心跳定时器，每20秒发送一次ping');
    }

    /**
     * 停止定时发送心跳
     */
    stopPing() {
        if (this.pingInterval) {
            clearInterval(this.pingInterval);
            this.pingInterval = null;
            console.log('已停止心跳定时器');
        }
    }

    /**
     * 处理接收到的消息
     * @param {Object} msg 消息对象
     */
    handleMessage(msg) {
        console.log('收到消息:', msg);
        switch(msg.type) {
            case 'response':
                this.handleResponse(msg);
                break;
            case 'notification':
                this.handleNotificationMsg(msg);
                break;
            case 'status':
                this.handleStatus(msg);
                break;
            case 'error':
                this.handleError(msg);
                break;
            case 'Pong':
                this.handlePong(msg);
                break;
            default:
                console.log('未知消息类型:', msg.type);
        }
    }

    /**
     * 处理响应消息
     * @param {Object} msg 消息对象
     */
    handleResponse(msg) {
        console.log('收到响应:', msg.data);
        
        if (this.onResponse) {
            this.onResponse(msg.data);
        }
    }

    /**
     * 处理通知消息
     * @param {Object} msg 消息对象
     */
    handleNotificationMsg(msg) {
        if (!msg.data || !msg.data.content) {
            console.log('收到空通知消息');
            return;
        }
        if (this.onNotification) {
            this.onNotification(msg.data);
        }
        let contentdic = msg.data.content;
        
        // 处理会议纪要
        if (contentdic.meeting_minutes && contentdic.meeting_minutes.content) {
            let meeting_minutes = contentdic.meeting_minutes.content;
            console.log('收到消息类型meeting_minutes:', meeting_minutes);
            if (this.handleNotification) {
                this.handleNotification(NotificationTypes.MeetingMinutes, meeting_minutes);
            }
        }
        
        // 处理侧边卡片（洞察、关键点、待办等）
        if (contentdic.sidecards && Array.isArray(contentdic.sidecards)) {
            console.log('sidecards:', contentdic.sidecards);
            
            contentdic.sidecards.forEach(element => {
                console.log('收到消息类型sidecards:', element.type);
                if (this.handleNotification && element.content) {
                    this.handleNotification(element.type, element.content);
                }
            });
        }
    }

    /**
     * 处理状态消息
     * @param {Object} msg 消息对象
     */
    handleStatus(msg) {
        console.log('状态更新:', msg.data);
        
        if (this.onStatus) {
            this.onStatus(msg.data);
        }
    }

    /**
     * 处理错误消息
     * @param {Object} msg 消息对象
     */
    handleError(msg) {
        console.error('服务器错误:', msg.data);
        
        if (this.onError) {
            this.onError(msg.data);
        }
    }

    /**
     * 处理心跳响应
     * @param {Object} msg 消息对象
     */
    handlePong(msg) {
        console.log('收到心跳响应');
        
        if (this.onHeartbeat) {
            this.onHeartbeat(msg);
        }
    }

    /**
     * 关闭连接
     */
    close() {
        this.stopPing();
        
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
        
        this.isConnected = false;
        this.sessionId = null;
        console.log('WebSocket连接已关闭');
    }

    /**
     * 获取连接状态
     * @returns {boolean} 是否已连接
     */
    getConnectionStatus() {
        return this.isConnected;
    }

    /**
     * 获取会话ID
     * @returns {string|null} 会话ID
     */
    getSessionId() {
        return this.sessionId;
    }
}

// 导出类（如果在Node.js环境中使用）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = MeetingAssistantClient;
}